<template>
  <div v-loading="loading" class="main">
    <el-container class="main">
      <el-header style="position: relative; height: 60px; z-index: 10" v-if="!hideNavBar">
        <el-menu class="menu_content" :default-active="activeIndex" :ellipsis="false" router mode="horizontal">
          <el-menu-item index="/">图库市场</el-menu-item>
          <el-menu-item index="/upload">我要上传</el-menu-item>
          <el-menu-item index="/myupload">我的上传</el-menu-item>
          <el-menu-item index="/mydownload">我的下载</el-menu-item>
          <el-menu-item index="/series">系列</el-menu-item>
          <el-menu-item index="/export">导出</el-menu-item>
          <div style="flex-grow: 1" />
          <el-menu-item>
            <el-avatar shape="square" @click="exit" :size="50">{{ username }}</el-avatar>
          </el-menu-item>
        </el-menu>
      </el-header>
      <el-main style="position: absolute; top: 60px; bottom: 0; width: calc(100% - 20px); overflow-y: auto">
        <RouterView />
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { RouterView } from 'vue-router';
import { ref, watch } from 'vue';
import router from './router';
import { useUserStore } from './stores/userInfo';
import { whoami } from './api/user';
import { ElMessageBox } from 'element-plus';
const activeIndex = ref('/');
const username = ref('');
const loading = ref(false);
const hideNavBar = ref(false);
watch(
  () => router.currentRoute.value,
  (to, from) => {
    const r = to;
    const login_require = !(r.name === 'login');
    hideNavBar.value = !login_require;
    const user = useUserStore();
    if (login_require) {
      if (!user.token) router.push('/login');
      else {
        activeIndex.value = to.path;
        loading.value = true;
        whoami()
          .then((r) => {
            loading.value = false;
            if (user.user?.UserName) {
              if (user.user?.UserName.length > 3) username.value = user.user?.UserName.substr(-3);
              else username.value = user.user?.UserName;
            }
          })
          .catch((e) => {
            loading.value = false;
          });
      }
    }
  },
  { immediate: true, deep: true }
);
const exit = () => {
  ElMessageBox.confirm('是否登出系统？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const user = useUserStore();
    user.log_out();
    router.push('/login');
  });
};
</script>

<style scoped>
.main {
  width: 100%;
  font-size: 14px;
}
.menu_content {
  width: 100%;
}
</style>
